import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import LoadingSpinner from '../common/LoadingSpinner';

const AdminRoute = ({ children }) => {
  const { isAuthenticated, isAdmin, loading } = useAuth();

  // 如果仍在加载认证状态，显示加载指示器
  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <LoadingSpinner />
      </div>
    );
  }

  // 如果未认证，重定向到登录页面
  if (!isAuthenticated) {
    return <Navigate to="/auth/login" replace />;
  }

  // 如果不是管理员，重定向到未授权页面或首页
  if (!isAdmin) {
    return <Navigate to="/" replace />;
  }

  // 如果是认证的管理员，渲染子组件
  return children;
};

export default AdminRoute;